﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BuildHelper.Work.JAVA;
using ProgNetComponentsDx.Options;
using ProgNetComponentsDx.Browsers;
using System.Data;

namespace BuildHelper.BHTasks
{
    public class JavaBuildTask : BaseProcesTask
    {
        public JavaBuildTask()
        {
            this.AlertImage = Properties.Resources.burn_java24;
        }

        [SerializeProperty]
        public string Brancz { get; set; }

        [SerializeProperty]
        public bool Clean { get; set; }
        [SerializeProperty]
        public int Server { get; set; }
        [SerializeProperty]
        public string Template { get; set; }
        [SerializeProperty]
        public bool Deploy { get; set; }
        [SerializeProperty]
        public bool UpdateBuildXml { get; set; }

        public JavaDataSet DataSet { get; set; }

        public bool IsDeploy { get; set; }
        private object lockArray = new object();

        private List<string> buildStm = new List<string>();
        private List<string> packStm = new List<string>();
        int buildStmIdx = 0;
        int packStmIdx = 0;
        private string CompileStm;
        private string PackStm;
        private string CurCommand;
        bool addAllDeploy = false;

        protected override string GetTaskName()
        {
            if(IsDeploy)
                return "Deployowanie [" + Brancz + "]";
            else
                return "Budowanie Javy [" + Brancz + "]";
        }
        protected override string GetAlertText()
        {
            if (IsDeploy)
                return GetTaskName();

            string text = "";
            text = "Kompilacja: " + buildStmIdx + "/" + buildStm.Count;
            if (CompileStm.IsNotNull())
                text += " (" + CompileStm + ")";
            
            text += Constants.NewLineLinux + "Pakowanie: " + packStmIdx + "/" + packStm.Count;
            if (PackStm.IsNotNull())
                text += " (" + PackStm + ")";
         
            if (CurCommand.IsNotNull())
            {
                if (text.IsNotNull())
                    text += Constants.NewLineLinux;
                text += "Komenda: " + CurCommand;
            }
            return text;
        }
        protected override string GetMsgForMemo(string msg)
        {
            string t = msg;
            if (OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Work_Group.Java.AddTimeToLog))
                t = DateTime.Now.ToString("G") + "    " + msg;
            return t;
        }

        List<string> FullErrorMsg = new List<string>();
        private bool ErrFound = false;

        protected override bool IsError(string msg)
        {
            if (IsDeploy)
                return msg.XMatch("The system cannot find the path specified");

            bool res = false;
            if (ErrFound)
            {
                lock (lockArray)
                {
                    if (FullErrorMsg.Count < 3)
                    {
                        if (!msg.XMatch("^\\s*\\[javac\\]\\s*\\^+\\s*$"))
                            FullErrorMsg.Add(msg);
                    }
                    else
                    {
                        res = true;
                    }
                }
            }
            else if (BudowanieJavyTools.FindError(msg))
            {
                lock (lockArray)
                {
                    FullErrorMsg.Add(msg);
                }
                ErrFound = true;
            }
            return res;
        }
        
        protected override bool ShouldAddMsgToMemo(string str)
        {
            if (str.XMatch("^" + BudowanieJavyTools.INFO_POCZATEK_DEPLOYOWANIA))
                addAllDeploy = true;
            if (str.XMatch("^" + BudowanieJavyTools.INFO_KONIEC_DEPLOYOWANIA))
                addAllDeploy = false;
            bool add = false;
            if (str.XMatch(BudowanieJavyTools.INFO_RESTART_SRV))
            {
                add = false;
                if (str.XMatch("^" + BudowanieJavyTools.INFO_RESTART_SRV))
                {
                    int srv = str.GetFirstMatch("^" + BudowanieJavyTools.INFO_RESTART_SRV + " (\\d*)").AsInt(-1);
                    if (srv > -1)
                    {
                        if (GlobalTools.ServerTools.IsServerRunning(srv))
                            GlobalTools.ServerTools.RunServer(srv, Brancz, OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Narzedzia.SerwerBringToFront), GlobalTools.ServerTools.ServerRestartType.Restart);
                    }
                }
            }
            else if (addAllDeploy && !str.XMatch("^echo"))
                add = true;

            else if (
                str.XMatch("^" + BudowanieJavyTools.INFO_KONIEC_BUDOWANIA) ||
              str.XMatch("^" + BudowanieJavyTools.INFO_POCZATEK_BUDOWANIA) ||
              str.XMatch("^" + BudowanieJavyTools.INFO_POCZATEK_DEPLOYOWANIA) ||
              str.XMatch("^" + BudowanieJavyTools.INFO_KONIEC_DEPLOYOWANIA))
            {
                add = true;
                str += " " + DateTime.Now.ToString("G");
            }
            else
                add = BudowanieJavyTools.ShouldAddLog(str);
            return add;
        }
        protected override void ProcessMessage(string str)
        {
            bool setText = false;
            if (str.XMatch("^\\w*:$"))
            {
                CurCommand = str.Replace(":", "");
                setText = true;
            }
            string stm = str.GetFirstMatch("^compile(\\w*):$");
            if (buildStm.ContainsIgnoreCase(stm))
            {
                if (CompileStm != stm)
                {
                    CompileStm = stm;
                    buildStmIdx++;
                    setText = true;
                }
            }
            if (str.XMatch("^prepareWebConfigs:"))
                stm = "Gcm";
            else
                stm = str.GetFirstMatch("^prepare(\\w*):$");

            if (packStm.ContainsIgnoreCase(stm))
            {
                if (PackStm != stm)
                {
                    PackStm = stm;
                    packStmIdx++;
                    setText = true;
                }
            }
            if (setText)
                this.UpdateTaskInfo();

        }
        protected override void ProcessError(string msg)
        {
            if (!IsDeploy)
            {
                string fullMsg = string.Empty;
                lock (lockArray)
                {
                    fullMsg = FullErrorMsg.AsString(" ");
                    FullErrorMsg.Clear();
                }
                ErrFound = false;
                Errors.Add(fullMsg);
                if (StopOnFirstError)
                    EndTask(TaskStatus.CanceledWithError);
            }
        }
        protected override void RunTask(System.Diagnostics.Process process)
        {
            buildStm.Clear();
            packStm.Clear();
            buildStmIdx = 0;
            packStmIdx = 0;
            CompileStm = string.Empty;
            PackStm = string.Empty;
            CurCommand = string.Empty;

            if (Template.IsNotNull())
            {
                DataSet = new JavaDataSet();
                BudowanieJavyTools.ReadTemplate(DataSet, Template);
            }
            else if (DataSet == null)
            {
                DataSet = new JavaDataSet();
                BudowanieJavyTools.ReadBranch(Brancz, DataSet);
            }

            DataRow[] rows = DataSet.BUILD.Select();
            foreach (DataRow r in rows)
            {
                if (r["STM"].AsString() != "GENESDK")
                {
                    if (r["Buduj"].AsBool())
                        buildStm.Add(r["STM"].AsString());
                    if (r["Pakuj"].AsBool())
                        packStm.Add(r["STM"].AsString());
                }
            }
            GlobalTools.ProcessTools.SetEnvVariable(process, Brancz);

            if (IsDeploy)
            {
                string path = BrowserCache.GetColumnValueForEditValue(Init.InitFormBrowserNames.Setup.Brancze, Brancz, "STP_BR_KATALOG").AsString();
                string gene = path.TrimEnd('\\') + @"\nd_src\gene";
                BudowanieJavyTools.DeployEar(this.Process, Server, gene, Brancz);
            }
            else
            {
                BudowanieJavyTools.BuildPack(process, DataSet, Clean, Brancz, Server, Deploy, UpdateBuildXml);
            }
        }
    }
}
